function $id(id){
    return document.getElementById(id);
}
function byClass(name, elem){
    return (elem || document).getElementsByClassName(name);
}

function playMovie(){
    var obj = $id('splayer');
    if (obj) {
        if (obj.paused) {
            obj.play();
        } else {
            obj.pause();
        }
    }
};
function loadMovie(source){
    var obj = $id('splayer');
    if (obj && obj.src.indexOf(source) == -1) {
        obj.src = source;
        obj.load();
    }
    playMovie(obj);
};
function toggleShow(objId, target){
    var obj = $id(objId);
    if (obj) {
        if (obj.style.display == 'none') {
            obj.style.display = '';
            target.className = 'hide';
            byClass('playBox')[0].style.width = '644px';
            byClass('primary', $id('body'))[0].style.width = '888px';
            byClass('primary', $id('body'))[0].style.borderRight = '1px solid #ccc';
            if (byClass('secondary', $id('body'))[0]) {
                byClass('secondary', $id('body'))[0].style.display = '';
            }
            if (byClass('primary', $id('footer'))[0]) {
                byClass('primary', $id('footer'))[0].style.width = '';
            }
        } else {
            obj.style.display = 'none';
            target.className = 'show';
            byClass('playBox')[0].style.width = 'auto';
            byClass('primary', $id('body'))[0].style.width = '980px';
            byClass('primary', $id('body'))[0].style.border = '0';
            if (byClass('secondary', $id('body'))[0]) {
                byClass('secondary', $id('body'))[0].style.display = 'none';
            }
            if (byClass('primary', $id('footer'))[0]) {
                byClass('primary', $id('footer'))[0].style.width = '980px';
            }
        }
    }
}
function highLight(obj) {
	$(obj).parent().parent().find('li').removeClass('active');
	$(obj).parent().addClass('active');
	var player = $id('splayer');
	if (player) {
		player.addEventListener('ended', function(){
			$(obj).parent().next().find('a').click();
		}, false);
	}
}
function clearLight(){
	$('#mainNav').find('li').removeClass('active');
}
function loadXML(xmlUrl, callback, current, add, add2){
    var cur = current || 1;
    $.ajax({
        url: xmlUrl,
        type: 'GET',
        dataType: 'xml',
        timeout: 3000,
        cache: false,
        error: function(xhr, textStatus, errorThrown){
            //alert(xhr.status+'，'+textStatus+'，'+errorThrown);
            //alert('加载文件出错，请稍候重试');
        },
        success: function(xml){
            callback(xml, cur, add, add2);
        }
    });
}

function toLink(mId, subId){
	window.first = false;
    var number = subId || 1;
    loadXML('/iface/ipadlist/' + mId + '/%E5%85%A8%E9%83%A8/%E5%85%A8%E9%83%A8/%E5%85%A8%E9%83%A8/' + number + '.xml', initChannel, mId);
}
function toPlay(mId){
    loadXML('/iface/vod/' + mId + '/1.xml', initPlayer, mId);
}
function toPlay2(mId){
    loadXML('/iface/vod/' + mId + '/1.xml', initPage, mId );
}
function toPage(mId,page){
    loadXML('/iface/vod/' + mId + '/'+page+'.xml', initPage, mId, page );
}
function goSeach(valSeach,mId){
    loadXML('/interface/search/ipad/1/q/'+ valSeach +'/index/'+mId+'/'+mId+'.xml', initSeach, valSeach, mId);
}
function toLive(mId, day, fresh){
    var day = day || 1;
    var now =new Date();
    var tmp = new Date(now - (day-1) * 24 * 60 * 60 * 1000);
    var y = tmp.getFullYear();
    var m = tmp.getMonth()+1;
    var d = tmp.getDate();
    if(m<10)m="0"+m;
    if(d<10)d="0"+d;
    var strdat = y+"-"+m+"-"+d;
    loadXML('/iface/live/' + mId + '/' + strdat + '.xml', initLivePlayer, mId, day, fresh);
}

function initMainNav(obj){
    var htmlStr = '';
    $(obj).find('navigation').each(function(i){
        var name = $(this).attr('text');
        var id = $(this).attr('id');
        var type = $(this).attr('type');
        htmlStr += '<li><a href="javascript:;" onclick="toLink(' + id + ');highLight(this);" class="nav" id="ch' + id + '" type="' + type + '">' + name + '</a></li>';
    });
    htmlStr = '<ul>' + htmlStr + '</ul>';
    $('#mainNav').append(htmlStr);
    //$('#ch1').click();
    $(".nav:first").trigger('click');
}

$('document').ready(function(){
		$('#seach').append('<input id="seach_input" class="seach_input" type="text" /><button id="seach_btn" class="seach_btn">搜索</button>');
	$('#seach_input').val("输入搜索条件").focus(function(){
		$(this).val("");
		});
	$('#seach_btn').click(function(){
		var seachval = $("#seach_input").val();
		seachval = encodeURIComponent(seachval);
		goSeach(''+seachval+'',1);
		});
	});
function initSeach(obj,valSeach){
	var page_count=$.trim($(this).find('page_count').text());
	var page=$.trim($(this).find('page').text());
	if(page_count > 1 && page < page_count){
		var nextStrx = '<a href="javascript:;" onclick="goSeach('+valSeach+','+(page+1)+')" class="nextChannel">下一页</a>'
		$('#footer').empty();
        $('#footer').append(nextStrx);
		}
	if(page_count > 1 && page_count-page > 1 ){
		var prevStrx = '<a href="javascript:;" onclick="goSeach('+valSeach+','+(page-1)+')" class="prevChannel">上一页</a>'
		$('#footer').empty();
        $('#footer').append(prevStrx);
	    }
		else{
			$('#footer').empty();
		}
	var htmlStr = '';
			$(obj).find('item').each(function(i){
			var imgurl=$.trim($(this).find('imgurl').text());
			var title = $.trim($(this).find('title').text());
			var showtip = $(this).attr('showtip');
			var vid = $(this).attr('vid');
			var type = $(this).attr('type');
			if (showtip==1){
			var tipStr='<span class="tip">' + title + '</span>'
			}
			else{
			var tipStr=''
				}
        if (type == 'vod') {
            htmlStr += '<li onclick="toPlay(' + vid + ');toPlay2('+ vid +');" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" >'+tipStr+'</li>';
        } else {
            htmlStr += '<li onclick="toLive(' + vid + ');toPlay2('+ vid +');" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" >'+tipStr+'</li>';
        }
		
         });
		htmlStr = htmlStr
		htmlStr = '<ul class="channel">' + htmlStr + '</ul>';

       	$('#body').empty();
		$("#body").append(htmlStr);
		clearLight();
}


function initChannel(obj, id){
    var pageCount = $(obj).find('page_count').text() - 0;
    var pageNow = $(obj).find('page').text() - 0;
    $('#footer').empty();
    if (pageCount > pageNow) {
        var nextStr = '<a href="javascript:;" onclick="toLink(' + id + ',' + (pageNow + 1) + ')" class="nextChannel">下一页</a>'
        $('#footer').append(nextStr);
    }
    if (pageNow != 1) {
        var prevStr = '<a href="javascript:;" onclick="toLink(' + id + ',' + (pageNow - 1) + ')" class="prevChannel">上一页</a>'
        $('#footer').append(prevStr);
    }
    var htmlStr = '';
    $(obj).find('main item').each(function(i){
        var imgurl = $.trim($(this).find('imgurl').text());
		var showtip = $(this).attr('showtip');
        var type = $(this).attr('type');
        var vid = $(this).attr('vid');
        var title = $.trim($(this).find('title').text());
		if (showtip==1){
			var tipStr='<span class="tip">' + title + '</span>'
			}
			else{
			var tipStr=''
				}
        if (type == 'vod') {
            htmlStr += '<li onclick="toPlay(' + vid + ');toPlay2('+ vid +')" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" >'+tipStr+'</li>';
        } else {
            htmlStr += '<li onclick="toLive(' + vid + ');toPlay2('+ vid +')" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" >'+tipStr+'</li>';
        }
    });
    htmlStr = '<ul class="channel">' + htmlStr + '</ul>';
    $('#body').empty();
    $('#body').append(htmlStr);
}
function initBest(obj, mId){
    var htmlStr = '';
    $(obj).find('main item').each(function(i){
        var imgurl = $.trim($(this).find('imgurl').text());
        var type = $(this).attr('type');
        var vid = $(this).attr('vid');
        var title = $.trim($(this).find('title').text());
        if (type == 'vod') {
            htmlStr += '<li onclick="toPlay(' + vid + ');toPlay2('+ vid +')" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" /></li>';
        } else {
            htmlStr += '<li onclick="toLive(' + vid + ');toPlay2('+ vid +')" style="background:url(' + imgurl + ');background-size:cover;" title="' + title + '" /></li>';
        }
    });
    if (mId != '0') {
        var extra = '<li class="back" /></li>';
        htmlStr = '<div class="secondary"><ul class="channel cLive">' + extra + htmlStr + '</ul></div>';
        $('#body').append(htmlStr);
        $('.secondary .cLive .back').bind('click', function() {
            toLive(mId);
        });
    } else {
        htmlStr = '<div class="secondary"><ul class="channel cLite">' + htmlStr + '</ul></div>';
        $('#body').append(htmlStr);
    }
}


function initPlayer(obj, mId){
    var vid=$(obj).find('item').attr('vid');
    var title = $.trim($(obj).find('title:first').text());
	var score = $(obj).find('item').attr('mark');
    var director = $.trim($(obj).find('director').text());
    var actor = $.trim($(obj).find('act').text());
    var imgurl = $.trim($(obj).find('imgurl').text());
    var content = $.trim($(obj).find('content').text());
    var file = $.trim($(obj).find('file').text());
	var page = $(obj).find('page').text();
	var pagecount = $(obj).find('page_count').text();
			if (pagecount > 1){
	var prevpage = page - 1;
    var nextpage = page - 0 + 1;
	var pageSrt='<div class="page"><span><a id="firstpage" onclick="toPage(' + vid +',1 )" title="第一页">第一页</a></span><span><a id="previous" onclick="toPage(' + vid +',1 )" title="上一页">上一页</a></span><span><a id="next" onclick="toPage(' + vid +',2)" title="下一页">下一页</a></span><span><a id="lastpage" onclick="toPage(' + vid +','+ pagecount +')" title="最后一页">最后一页</a></span></div>'
		}else{
	var pageSrt=''
			}
	var titleStr='<h2>'+title+'</h2>';
    var picStr = '<div class="pic"><img src="' + imgurl + '" width="120" height="158" title="' + title + '" /></div>';
    var scoreStr = '<div class="score">评分：<br /><span class="num">' + score + '</span></div>';
    var castStr = '<div class="cast">导演：' + director + '<br />主演：' + actor + '</div>';
    var textStr = '<div class="text">剧情: <br />' + content + '</div>';
    var playBoxStr = '<div id="playBox" class="playBox"><h1>' + title + '</h1><video id="splayer" width="100%" height="520" controls="controls" autoplay="autoplay"><source src="' + file + '" type="video/mp4" title="第一集"/></video></div>';
	
    htmlStr = '<div class="primary"><div id="infoBox"><div class="infoBox">' + titleStr + picStr + castStr +'<div id="videoxxx"></div>'+pageSrt+'</div></div>' + playBoxStr + '</div>'
	$('#body').empty();
    $('#body').append(htmlStr);
    loadMovie(file);
    $('#footer').empty();
    var prevFile = mId - 1;
    var nextFile = mId - 0 + 1;
    var prevPlay = prevFile ? 'toPlay(' + prevFile + ');' : '';
    var nextPlay = nextFile ? 'toPlay(' + nextFile + ');' : '';
    var footStr = '<div class="infoCtrl"><a href="javascript:;" onclick="toggleShow(\'infoBox\',this);" class="hide">显示/隐藏</a></div><div class="primary"><div class="playCtrl"><a href="javascript:;" onclick="' + prevPlay + '" class="prev">上一个</a> <a href="javascript:;" onclick="playMovie();" class="play">播放</a> <a href="javascript:;" onclick="' + nextPlay + '" class="next">下一个</a> </div></div>';
    $('#footer').append(footStr);
    loadXML('/iface/ipadlist/' + $('#header').find('.active a')[0].id.substring(2) + '/best.xml', initBest, '0');
}
function initPage(obj, mId){
	var video_list=$(obj).find('video_list').attr('title');
	var state= $(obj).find('item').attr('state');
	var vid=$(obj).find('item').attr('vid');
	var linenum= $(obj).find('video_list').attr('linenum');
	var pagecount = $(obj).find('page_count').text();
	var page = $(obj).find('page').text();
	var title = $.trim($(obj).find('title:first').text());
	var htmlStr = '';
    $(obj).find('video').each(function(i){
        var title = $.trim($(this).find('title').text());
		var url = $.trim($(this).find('url').text());
		var urlStr =url;
            htmlStr += '<li url='+url+' title='+title+'><a title="'+ title +'" href="javascript:;">'+title+'</a></li>';
			
		});
    if (state>1 && linenum==3){
		var htmlStr = '<span class="title">'+video_list+'</span><span class="num">'+state+'集全</span><ul id="videoul">'+htmlStr+'</ul>';
		$("#videoxxx").addClass("videolist")

		}
	else if (state>1 && linenum==1){
	var htmlStr = '<span class="title">'+video_list+'</span><ul id="videoul">'+htmlStr+'</ul>';
    $("#videoxxx").addClass("videolist2")
	}else{
		}
    
	$("#videoxxx").empty();
	$("#videoxxx").append(htmlStr);

    var playurl=$('#splayer').find('source').attr('title');

	$("#videoxxx").find('li[title="'+playurl+'"]').addClass("playbtn");
	
	$("#videoxxx").find('li').click(function(){
	$("#videoxxx > ul > li").removeClass("playbtn");
	var urlx=$(this).attr("url");
	var title=$(this).text();
	$(this).addClass("playbtn");
	$("#playBox").empty();
	$("#playBox").append('<h1>' + title + '</h1><video id="splayer" width="100%" height="520" controls="controls" autoplay="autoplay"><source src="' + urlx + '" title="'+ title +'" type="video/mp4" /></video>');
	
	});
	
	}

function initLivePlayer(obj, mId, day, fresh){
    var monthArray = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    var weekArray = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var today = new Date();
    var hour = today.getHours();
    var min = today.getMinutes();
    var yesterday = new Date(today - 24 * 60 * 60 * 1000);
    var beforeday = new Date(today - 48 * 60 * 60 * 1000);
    if (today.getDay() == 0 || today.getDay() == 6) {
    	todaySunday = ' weekend'
    } else {
    	todaySunday = '';
    }
    if (yesterday.getDay() == 0 || yesterday.getDay() == 6) {
    	yesterdaySunday = ' weekend'
    } else {
    	yesterdaySunday = '';
    }
    if (beforeday.getDay() == 0 || beforeday.getDay() == 6) {
    	beforedaySunday = ' weekend'
    } else {
    	beforedaySunday = '';
    }
    var todayNow = (day == 1)?' today':'';
    var yesterdayNow = (day == 2)?' today':'';
    var beforedayNow = (day == 3)?' today':'';
    var todayStr = '<div class="day' + todaySunday + todayNow + '" onclick="toLive(' + mId + ',1,\'nore\')">' + today.getFullYear() + '年<br />' + monthArray[today.getMonth()] + '月<strong>' + today.getDate() + '</strong>' + weekArray[today.getDay()] + '</div>';
    var yesterdayStr = '<div class="day' + yesterdaySunday + yesterdayNow + '" onclick="toLive(' + mId + ',2,\'nore\')">' + yesterday.getFullYear() + '年<br />' + monthArray[yesterday.getMonth()] + '月<strong>' + yesterday.getDate() + '</strong>' + weekArray[yesterday.getDay()] + '</div>';
    var beforedayStr = '<div class="day' + beforedaySunday + beforedayNow + '" onclick="toLive(' + mId + ',3,\'nore\')">' + beforeday.getFullYear() + '年<br />' + monthArray[beforeday.getMonth()] + '月<strong>' + beforeday.getDate() + '</strong>' + weekArray[beforeday.getDay()] + '</div>';
    var file = $.trim($(obj).find('streamer').text());
    var title = $.trim($($(obj).find('title')[0]).text());
    var playBoxStr = '<div class="playBox"><h1>' + title + '</h1><video id="splayer" width="100%" height="520" controls="controls" autoplay="autoplay"><source src="' + file + '" type="video/mp4" /></video></div>';
    var scheduleStr = '';
    var scrollrow = 0;
    $(obj).find('video_list video').each(function(i){
        var start = $(this).attr('start');
        var end = $(this).attr('end');
        var file = $.trim($(this).find('m3u8').text());
        var start_d = start.substring(0,start.indexOf(' '))
        start_d = start_d.replace(/-/g, '/');
        var start_t = start.substring(start.indexOf(' '))
        var end_d = end.substring(0,end.indexOf(' '))
        end_d = end_d.replace(/-/g, '/');
        var end_t = end.substring(end.indexOf(' '))
        var active = '';
        var date1 = new Date(start_d + start_t);
        var date2 = new Date(end_d + end_t);
        var date = new Date();
        if ((date >= date1) && (date <= date2)) {
            active = ' class="active"';
            scrollrow = i;
        }
        var startTime = start.substring(start.indexOf(' '), 16);
        var title = $.trim($(this).find('title').text());
        if (date < date1) {
        	scheduleStr += '<li' + active + '><a href="javascript:;">' + startTime + ' ' + title + '</a></li>';
        } else {
        	scheduleStr += '<li' + active + '><a href="javascript:;" onclick="loadMovie(\'' + file + '\');highLight(this);">' + startTime + ' ' + title + '</a></li>';
        }
    });
    scheduleStr = '<div class="schedule"><ul>' + scheduleStr + '</ul></div><a href="javascript:;" ontouchstart="roll(-1);" ontouchend="clearRoll();" class="rollUp">上滚</a><a href="javascript:;" ontouchstart="roll(1);" ontouchend="clearRoll();" class="rollDown">下滚</a>';
    var infoBoxStr = '<div id="infoBox"><div class="infoBox"><div class="calendar">' + beforedayStr + yesterdayStr + todayStr + '</div>' + scheduleStr + '</div></div>';
    if (fresh) {
         $('#body .primary #infoBox').replaceWith(infoBoxStr);
    } else {
        var htmlStr = '<div class="primary">'+ infoBoxStr + playBoxStr + '</div>';
       if (!window.first) {
            $('#body').empty();
            $('#body').append(htmlStr);
        } else {
            $('#body .primary').replaceWith(htmlStr);
            $('.secondary .cLive .back').unbind('click');
            $('.secondary .cLive .back').bind('click', function() {
                toLive(mId);
            });
        }
        $('#body').find('.schedule')[0].scrollTop = 35 * scrollrow;
        loadMovie(file);

        $('#footer').empty();
        var footStr = '<div class="infoCtrl"><a href="javascript:;" onclick="toggleShow(\'infoBox\',this);" class="hide">显示/隐藏</a></div>';
        $('#footer').append(footStr);
        if (!window.first) {
            loadXML('/iface/ipadlist/' + $('#header').find('.active a')[0].id.substring(2) + '/best.xml', initBest, mId);
            window.first = true;
        }
    }
}

function rollBase(direct) {
	if (direct>0) {
		$('#body').find('.schedule')[0].scrollTop += 3;
	} else {
		$('#body').find('.schedule')[0].scrollTop -= 3;
	}
}
var myInterval;
function roll(direct) {
	if (myInterval) {
		clearInterval(myInterval);
	}
	myInterval = setInterval(function(){
		rollBase(direct);
	}, 50);
}
function clearRoll() {
	if (myInterval) {
		clearInterval(myInterval);
	}
}
